package service;

import Bean.Book;
import Bean.Page;
import DAO.BookDAO;
import DAO.BookDAOImpl;

import java.util.List;

/**
 * @author jianjun
 * @Describe
 * @creat 2021-12-23-10:31
 */
public class BookServiceImpl implements BookService {
    BookDAO bookDAO = new BookDAOImpl();

    @Override
    public int addBook(Book book) {
        return bookDAO.addBook(book);
    }

    @Override
    public int deleteBook(Integer id) {
        return bookDAO.deleteBook(id);
    }

    @Override
    public int updateBook(Book book) {
        return bookDAO.updateBook(book);
    }

    @Override
    public Book queryBookById(Integer id) {
        return bookDAO.queryBookById(id);
    }

    @Override
    public List<Book> query() {
        return bookDAO.query();
    }

    @Override
    public Page page(Integer pageNo, Integer pageSize) {
        //总记录数
        Integer pageTotalCount = bookDAO.queryForPageTotalCount();
        //总页码
        int pageTotal = pageTotalCount / pageSize;
        if ((pageTotalCount % pageSize) > 0) {
            pageTotal++;
        }
        // 数据边界的有效检查
        if (pageNo < 1){
            pageNo = 1;
        }
        if (pageNo > pageTotal){
            pageNo = pageTotal;
        }
        //当前页数据
        // 先把每页的头个书籍的 id 求出来 pageBegin = (pageNo - 1) * pageSize
        int pageBegin = (pageNo - 1) * pageSize;
        List<Book> books = bookDAO.queryForItems(pageBegin, pageSize);
        return new Page(pageNo,pageTotal,pageTotalCount,pageSize,books);
    }

    @Override
    public Page pageByPreice(Integer pageNo, Integer pageSize, Integer minPrice, Integer maxPrice) {
        //总记录数
        Integer pageTotalCount = bookDAO.queryForPageTotalCount(minPrice,maxPrice);
        //总页码
        int pageTotal = pageTotalCount / pageSize;
        if ((pageTotalCount % pageSize) > 0) {
            pageTotal++;
        }
        // 数据边界的有效检查
        if (pageNo < 1){
            pageNo = 1;
        }
        if (pageNo > pageTotal){
            pageNo = pageTotal;
        }
        //当前页数据
        // 先把每页的头个书籍的 id 求出来 pageBegin = (pageNo - 1) * pageSize
        int pageBegin = (pageNo - 1) * pageSize;
        List<Book> books = bookDAO.queryForItems(pageBegin, pageSize,minPrice,maxPrice);
        return new Page(pageNo,pageTotal,pageTotalCount,pageSize,books);
    }
}
